from common.serializers import ExcludeableSeri
from school.serializers import SchoolSeri
from .models import *
from rest_framework import serializers
from accounts.serializers import UserSeri


class TextBookSeri(serializers.ModelSerializer):
    """Seri TextBook"""
    textbook = serializers.StringRelatedField()

    class Meta:
        model = STextBook
        fields = ('pk', 'textbook', 'path', 'thumbnail')


class SClassSerializer(ExcludeableSeri):

    students = serializers.SerializerMethodField('my_student')
    textbooks = TextBookSeri(many=True, required=False)

    def create(self, validated_data):
        clz = SClass(**validated_data)
        clz.save()

        for s in self.initial_data.get('students', []):
            student_pk = s.get('pk', None)
            if student_pk:
                student = Student.objects.get(pk=int(student_pk))
            else:
                seri_student = StudentSerializer(data=s)
                seri_student.is_valid()
                student = seri_student.save()
            student.classes.add(clz)

        return clz

    def update(self, instance, validated_data):
        instance.weekday = validated_data.get('weekday', instance.weekday)
        instance.begin = validated_data.get('begin', instance.begin)
        instance.duration = validated_data.get('duration', instance.duration)
        instance.fee = validated_data.get('fee', instance.fee)
        instance.ccolor = validated_data.get('ccolor', instance.ccolor)
        instance.color_custom = validated_data.get('color_custom', instance.color_custom)
        instance.save()
        return instance

    def my_student(self, clz):
        students = clz.class_students.all()
        res = []
        for s in students:
            res.append({'pk': s.pk, 'fee': s.fee, 'me': UserSeri(s.me, context={'excludes': ['videos', 'student', 'teacher', 'schools']}).data})
        return res

    class Meta:
        model = SClass
        fields = ('weekday', 'begin', 'duration', 'ccolor', 'color_custom', 'students', 'pk', 'textbooks')


class SCommentSerializer(serializers.ModelSerializer):
    textbook = serializers.StringRelatedField()

    class Meta:
        model = SComment
        fields = ('score', 'textbook', 'content', 'create_date')


class StudentSerializer(ExcludeableSeri):
    me = UserSeri(context={'excludes': ['videos', 'student', 'teacher', 'schools']})
    classes = SClassSerializer(many=True, required=False)
    comments = SCommentSerializer(many=True, required=False)
    student_schools = serializers.PrimaryKeyRelatedField(read_only=True, many=True, required=False)

    def create(self, validated_data):
        json_me = validated_data.get('me', {})
        me_pk = json_me.get('pk', None)

        if me_pk:
            obj_me = User.objects.get(pk=int(me_pk))
            return Student.objects.get(me=obj_me)
        else:
            me = UserSeri(data=json_me)
            me.is_valid()
            obj_me = me.save()
            try:
                student = Student.objects.get(me=obj_me)
            except Exception as e:
                student = Student.objects.create(me=obj_me)
            student.save()
            return student

    def update(self, instance, validated_data):
        instance.fee = validated_data.get('fee', instance.fee)
        instance.save()
        return instance

    class Meta:
        model = Student
        fields = ('pk', 'me', 'classes', 'comments', 'student_schools', 'fee')

